import { createRouter, createWebHistory } from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css"; //引入样式
import { useLocalStorage } from "@vueuse/core";
import { initStaticRouterAndMenu, staticRouter } from "./modules/staticRouter";
import { initDynamicRouter } from "./modules/dynamicRouter";
import { TOKEN_KEY } from "../utils/constants";
import { useAuthMenu } from "../store/authMenu";
import { OPEN_DYNAMIC_ROUTER } from "@/config/config";
import { APP_NAME } from "../config/config";

NProgress.configure({ showSpinner: false });

const router = createRouter({
  history: createWebHistory("/"),
  routes: [...staticRouter],
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

// 白名单路由
const whiteList = ["/login", "/404", "/403"];

router.beforeEach((to, from, next) => {
  const token = useLocalStorage(TOKEN_KEY, "");

  NProgress.start();
  const toPath = to.path;
  if (whiteList.includes(toPath)) {
    return next();
  }
  if (!token.value) {
    return next({ path: "/login", query: { redirect: toPath }, replace: true });
  }
  //初始化路由和菜单
  const authMenu = useAuthMenu();
  if (!authMenu.staticMenuList) {
    initStaticRouterAndMenu();
  }
  if (!authMenu.dynamicMenuList && OPEN_DYNAMIC_ROUTER) {
    initDynamicRouter();
    return next({ ...to, replace: true });
  }
  next();
});

router.afterEach((to) => {
  NProgress.done();
  document.title = `${APP_NAME}-${to.meta.title}`;
});

router.onError((error) => {
  NProgress.done();
  console.warn("路由错误", error.message);
});

export default router;
